<?php

class PembayaranPinjamanController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/template';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','Delete_Bayar'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex($id)
	{
		$criteria = new CDbCriteria;
		$criteria->condition="ID_PINJAMAN=".$id;
		$pinjaman = Pinjaman::model()->find('ID_PINJAMAN='.$id);
		
			if (isset($_REQUEST['sSearch']) && isset($_REQUEST['sSearch']{0})) {
				  
			 }

			$sort = new EDTSort('PembayaranPinjaman', array('TANGGAL_TRANSAKSI','JUMLAH_BAYAR'));
			 $sort->defaultOrder = array('TANGGAL_TRANSAKSI'=>CSort::SORT_DESC);
			 $pagination = new EDTPagination();
			 
			 $dataProvider = new CActiveDataProvider('PembayaranPinjaman', array(
				  'criteria'      => $criteria,
				  'pagination'    => $pagination,
				  'sort'          => $sort,
			 ));
			 
			$widget=$this->createWidget('ext.EDataTables.EDataTables', array(
			 'id'            => 'PembayaranPinjaman',
			 'dataProvider'  => $dataProvider,
			 'ajaxUrl'       => Yii::app()->getBaseUrl().'/index.php/PembayaranPinjaman/index/'.$id,
			 'columns'       => array(
									array(
									'name'=>'TANGGAL_TRANSAKSI',
									'value'=>'date("d-m-Y",strtotime($data->TANGGAL_TRANSAKSI))',
									),
									array(
									'name'=>'JUMLAH_BAYAR',
									'value'=>'"Rp ".number_format($data->JUMLAH_BAYAR,2,",",".")',
									),
									array(
									'name'=>'KETERANGAN',
									'value'=>'$data->KETERANGAN',
									),
									array(
        'class'=>'ext.EDataTables.EButtonColumn',
		'template'=>'{delete}',
		'header'=>'Hapus Histori Pembayaran',
		'buttons'=>array(
					'delete'=>array(
			'label'=>'Hapus Histori Pembayaran',
'url'=>'Yii::app()->createUrl("PembayaranPinjaman/Delete_Bayar/".$data->ID_BAYAR."/"."'.$id.'")',
			'imageUrl'=>Yii::app()->request->baseUrl.'/images/grid/deleted.png',
									),
							),
        'deleteConfirmation'=>"js:'Hapus Histori Pembayaran pada Tanggal  '+$(this).parent().parent().children(':first-child').text()+' dengan Jumlah '+$(this).parent().parent().children(':nth-child(2)').text()+' dari daftar?'",		),
								),
			'buttons' => array(
					// 'refresh' => null,
					'print' => null,
					'export' => null,
					'klaim' => array(
								 'label' => 'Bayar Cicilan',
								 'text' => true,
								 'htmlClass' => 'refreshButton',
								 'icon' => 'ui-icon-document',
'callback' => 'js:function(){document.location.href = \''.Yii::app()->request->baseUrl.'/index.php/PembayaranPinjaman/create/'.$id.'\';}',
								),
					'back' => array(
								 'label' => 'Kembali',
								 'text' => true,
								 'htmlClass' => 'refreshButton',
								 'icon' => 'ui-icon-document',
'callback' => 'js:function(){document.location.href = \''.Yii::app()->request->baseUrl.'/index.php/Pinjaman/view/'.$pinjaman->ID_ANGGOTA.'\';}',
								),
				)
			 
			));		
		
			if (!Yii::app()->getRequest()->getIsAjaxRequest()) {
				$this->render('index', array('widget' => $widget));
				return;
			} else {
			  echo json_encode($widget->getFormattedData(intval($_REQUEST['sEcho'])));
			  Yii::app()->end();
			}
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($id)
	{
		$model=new PembayaranPinjaman;
		$model->ID_PINJAMAN = $id;
		$model_pinjaman = Pinjaman::model()->find('ID_PINJAMAN='.$id);
		$anggota = Anggota::model()->findByPk($model_pinjaman->ID_ANGGOTA);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['PembayaranPinjaman']))
		{
			$model->attributes=$_POST['PembayaranPinjaman'];
			$model->TANGGAL_TRANSAKSI = date('Y-m-d', strtotime($_POST['PembayaranPinjaman']['TANGGAL_TRANSAKSI']));
			$model_pinjaman->CICILAN_TERBAYAR = $model_pinjaman->CICILAN_TERBAYAR + 1;
			$model_pinjaman->SALDO = $model_pinjaman->SALDO - $model->JUMLAH_BAYAR;
			
			if($model_pinjaman->SALDO <= 0){
				$model_pinjaman->STATUS_LUNAS = 1;
			}
			
			if($model->save()){
				$model_pinjaman->save();
				$this->otomasiJurnal($model->TANGGAL_TRANSAKSI,$anggota->NAMA,$model->JUMLAH_BAYAR,$id);
				$this->redirect(array('index','id'=>$id));
			}
		}

		$this->render('create',array(
			'model'=>$model,'model_pinjaman'=>$model_pinjaman
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['PembayaranPinjaman']))
		{
			$model->attributes=$_POST['PembayaranPinjaman'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ID_BAYAR));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
	
	
	public function actionDelete_Bayar($id,$idx)
	{
		$history = PembayaranPinjaman::model()->find("ID_BAYAR=".$id);
		
		if($history->delete()){
			$pinjaman = Pinjaman::model()->find("ID_PINJAMAN=".$idx);
			$pinjaman->JUMLAH_PINJAMAN = $pinjaman->JUMLAH_PINJAMAN + $history->JUMLAH_BAYAR;
			$pinjaman->SALDO = $pinjaman->SALDO + $history->JUMLAH_BAYAR; 
			$pinjaman->CICILAN_TERBAYAR = $pinjaman->CICILAN_TERBAYAR - 1;
			
			if($pinjaman->SALDO > 0){
				$pinjaman->STATUS_LUNAS = 0;
			}
			
			if ($pinjaman->save()){
				$this->redirect(array('index','id'=>$idx));
			}
		}
	}
	
	
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new PembayaranPinjaman('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PembayaranPinjaman']))
			$model->attributes=$_GET['PembayaranPinjaman'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=PembayaranPinjaman::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='pembayaran-pinjaman-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function otomasiJurnal($tanggal,$nama,$jumlah,$id_pinjaman){
		$otomasi = AkunOtomasi::model()->findByPk(3);
				
				$jurnal = new Jurnal;
				$last_jurnal = Jurnal::model()->find(array("order" => "ID_JURNAL DESC"));
				
				if ($last_jurnal == null){
					$no_jurnal = 1;
				}
				else {
					$split = explode("-",$last_jurnal->NO_JURNAL);
					$no_jurnal = $split[1] + 1;
				}
				
				$jurnal->NO_JURNAL = "JU-".$no_jurnal;
				$jurnal->TANGGAL = $tanggal;
				$jurnal->KETERANGAN = "Pinjaman ".$nama;
				
				$jurnal->save();
				
				$help = new HelpPinjamanJurnal;
				$help->ID_PINJAMAN = $id_pinjaman;
				$help->ID_JURNAL = $jurnal->ID_JURNAL;
				
				$help->save();
				
				$jurnal_detail_debet = new JurnalDetail;
				$jurnal_detail_debet->ID_JURNAL = $jurnal->ID_JURNAL;
				$jurnal_detail_debet->ID_AKUN = $otomasi->OTOMASI_DEBET;
				$jurnal_detail_debet->DEBIT_KREDIT = 0;
				$jurnal_detail_debet->NILAI = $jumlah;
				
				$jurnal_detail_debet->save();
				
				$jurnal_detail_kredit = new JurnalDetail;
				$jurnal_detail_kredit->ID_JURNAL = $jurnal->ID_JURNAL;
				$jurnal_detail_kredit->ID_AKUN = $otomasi->OTOMASI_KREDIT;
				$jurnal_detail_kredit->DEBIT_KREDIT = 1;
				$jurnal_detail_kredit->NILAI = $jumlah;
				
				$jurnal_detail_kredit->save();
	}
}
